package dawn.util;

import java.util.Arrays;

public class BitUtil {
    public static boolean get(byte[] bytes, int position) {
        if (position > bytes.length * 8)
            return false;

        int bitOffset = position % 8;
        int byteOffset = position / 8;

        return (byte) (bytes[byteOffset] & (1 << bitOffset)) != 0;
    }

    public static byte[] set(byte[] bytes, int position) {
        if (position > bytes.length * 8)
            bytes = expend(bytes, position);

        int bitOffset = position % 8;
        int byteOffset = position / 8;

        bytes[byteOffset] |= (byte) (1 << bitOffset);
        return bytes;
    }

    public static byte[] expend(byte[] bytes, int length) {
        if (bytes.length > length / 8 + 1)
            return bytes;
        bytes = Arrays.copyOf(bytes, length / 8 + 1);
        return bytes;
    }

    public static void main(String[] args) {
        byte[] bytes = new byte[1];
        System.out.println(get(bytes, 1));
        bytes = set(bytes, 1);
        System.out.println(get(bytes, 1));
        System.out.println(get(bytes, 1));
        System.out.println(get(bytes, 1));

        System.out.println(get(bytes, 20));
        bytes = set(bytes, 20);
        System.out.println(get(bytes, 20));
    }
}
